<template>
  <div class="page">
    <v-pageTitle title="角色管理"></v-pageTitle>
    <imp-panel>
      <v-pageSearch>
        <el-row style="width: 100%;">
          <el-form :inline="true">
            <el-col :span="16">
              <el-form-item label="角色">
                <el-select size="small" v-model="formSearch.staff" filterable placeholder="请选择查询关键字">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="onSearch">查询</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="float: right;">
                <el-button  type="danger" :disabled="this.sels.length===0" @click="del" size="small">删除</el-button>
              </el-form-item>
              <el-form-item style="float: right;">
                <el-button  type="primary" @click="batchAdd" size="small">新增角色</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </v-pageSearch>
    
      <v-pageTable pagination :sizeChange="sizeChange" :pageChange="pageChange" :paginationTotal="paginationTotal" paginationAlign="right">
        <el-table v-loading="tableData.loading" :data="tableData.body" border style="width: 100%" @selection-change="selsChange" :default-sort="{prop: 'date', order: 'descending'}">
            <el-table-column fixed type="selection" width="50">
            </el-table-column>
            <el-table-column type="index" label="序号" width="80" align="center">
            </el-table-column>
            <el-table-column prop="flag" label="标识" width="120" sortable>
            </el-table-column>
            <el-table-column prop="name" label="角色名称" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" sortable>
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status | statusFilterType">{{scope.row.status | statusFilter}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150" sortable>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="255">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="default"
                  icon="edit"
                  @click="batchEdit(scope.row)">编辑
                </el-button>
                <el-button
                  size="small"
                  type="info"
                  icon="setting"
                  @click="handleRoleConfig(scope.$index, scope.row)">配置权限
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDel(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
        </el-table>
      </v-pageTable>
    </imp-panel>

    <!--配置界面-->
    <el-dialog title="配置用户角色" v-model="dialogVisible" size="tiny">
      <div class="select-tree">
        <el-scrollbar
          tag="div"
          class='is-empty'
          wrap-class="el-select-dropdown__wrap"
          view-class="el-select-dropdown__list">
          <el-tree
            ref="roleTree"
            :data="roleTree"
            show-checkbox
            check-strictly
            node-key="id" v-loading="dialogLoading"
            :props="defaultProps">
          </el-tree>
        </el-scrollbar>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="configUserRoles">确 定</el-button>
        </span>
    </el-dialog>

    <!--编辑界面-->
    <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色标识" prop="flag">
          <el-input type="number" v-model="ruleForm.flag"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch on-text="" off-text="" v-model="ruleForm.status"></el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="ruleForm.remark">
          </el-input>
        </el-form-item>
        <el-form-item label="当前时间">
          <h3 style="font-weight:400;">{{nowDate}}</h3>
        </el-form-item>
        <el-form-item>
            <el-button  type="primary" @click.native="submitForm('ruleForm')" :loading="editLoading">提交</el-button>
            <el-button  @click.native="editFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import panel from "@/components/common/panel.vue"
import util from '../../util/util'
  export default {
    components: {
      'imp-panel': panel
    },
    data() {  
      return {
        tableData: {
            loading: true,
            head: [],
            body: []
        },
        options: [
          {
            value: '选项1',
            label: '普通用户'
          }, {
            value: '选项2',
            label: '主管经理'
          }, {
            value: '选项3',
            label: '管理员'
          }
        ],
        formSearch:{
          staff: ''
        },
        paginationTotal: 100,
        sels:[],

        //编辑界面数据
				ruleForm: {
          flag: '',
          name: '',
          status: false,
          remark: ''
        },
        rules: {
          flag: [
            { required: true, message: '请输入角色标识', trigger: 'blur' }
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          remark: [
            { required: false, message: '请填写备注', trigger: 'blur' }
          ]
        },
        editFormVisible: false,//编辑界面是否显示


        editLoading: false,
        dialogVisible: false,
        dialogLoading: false,
        defaultProps: {
          children: 'children',
          label: 'name',
          id: "id",
        },
        roleTree: [
            {
                "id":26,
                "delFlag":0,
                "parentId":null,
                "sort":0,
                "name":"超级管理员",
                "enName":"super_manager",
                "usable":"1",
                "remarks":"",
                "children":[

                ]
            },
            {
                "id":27,
                "delFlag":0,
                "parentId":null,
                "sort":1,
                "name":"客服主管",
                "enName":"server_manager",
                "usable":"1",
                "remarks":"",
                "children":[
                    {
                        "id":28,
                        "delFlag":0,
                        "parentId":27,
                        "sort":0,
                        "name":"售后客服",
                        "enName":"server1",
                        "usable":"1",
                        "remarks":"",
                        "children":[

                        ]
                    },
                    {
                        "id":29,
                        "delFlag":0,
                        "parentId":27,
                        "sort":1,
                        "name":"售前客服",
                        "enName":"server2",
                        "usable":"1",
                        "remarks":"",
                        "children":[

                        ]
                    }
                ]
            }
        ],

        nowDate: util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    filters: {
      statusFilter(statue) {
        let sta = statue ? 1 : 0;
        let statusMap = ['禁用','启用']
        return statusMap[sta]
      },
      statusFilterType(statue) {
        let sta = statue ? 1 : 0;
        let statusMapType = ['error','success']
        return statusMapType[sta]
      }
    },
    methods: {
      onSearch(formSearch){
        console.log(formSearch)
      },
      getTableData(data) {
        // ajax 查询表格数据
        this.tableData.body = [
          {
            id: 1,
            flag: '150000001',
            name: '普通用户',
            status: true,
            remark: '只有基础权限'
          }, {
            id: 2,
            flag: '150000002',
            name: '主管经理',
            status: true,
            remark: '考核权限'
          }, {
            id: 3,
            flag: '150000003',
            name: '管理员',
            status: true,
            remark: '所有权限'
          }
        ]
        // 模拟加载
        setTimeout(() => {
            this.tableData.loading = false
        }, 1000)
      },
      sizeChange(val){
        this.getTableData()
      },
      pageChange(val){
        this.getTableData()
      },
      selsChange: function (sels) {
				this.sels = sels;
			},
      handleClick(row) {
        console.log(row);
      },
      //显示新增界面
      batchAdd(){
        this.editFormVisible = true;
      },
      //显示编辑界面
			batchEdit: function (row) {
				this.editFormVisible = true;
				this.ruleForm = Object.assign({}, row);
			},
      batchClick(){
        // var ids = this.sels.map(item => item.id).toString();
				console.log(this.sels)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
            this.editFormVisible = false;
            this.dialogVisible = true;
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该员工吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
      del: function (index, row) {
				this.$confirm('确认删除该员工吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
      // 配置事件
      handleRoleConfig(index, row){
        this.currentRow = row;
        this.dialogVisible = true;
        // if (this.roleTree.length <= 0) {
        //   sysApi.roleList({selectChildren:true})
        //     .then(res => {
        //       this.roleTree = res
        //     })
        // }
        // this.$http.get(api.SYS_USER_ROLE + "?id=" + row.id)
        //   .then(res => {
        //     this.$refs.roleTree.setCheckedKeys(res.data);
        //   }).catch(err=>{

        // })
      },
      configUserRoles(){
        // let checkedKeys = this.$refs.roleTree.getCheckedKeys();
        //   this.$http.get(api.SYS_SET_USER_ROLE + "?userId=" + this.currentRow.id + "&roleIds="+checkedKeys.join(','))
        //   .then(res => {
        //       this.$message('修改成功');
        //       this.dialogVisible = false;
        //   })
      },
    },
    watch: {
      //第一种写法 适用于普通变量（简单类型的值的观测写法）
      // 关闭dialog的时候 初始化页面表单数据
      editFormVisible: function (val, oldVal) {
        console.log('new: %s, old: %s', val, oldVal)
        if(!val){
          console.log(this.ruleForm)
          this.ruleForm = {
            userName: '',
            name: '',
            gender: 0,
            tel: '',
            email: '',
            branch: '',
            post: '',
            status: false,
            mark: ''
          }
        }
      }
    },
    mounted() {
        // 获取table数据
        this.getTableData()

        let  _this = this;
        this.timer = setInterval(function(){
            _this.nowDate = util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss');
        },1000);
    },
    beforeDestory(){
        if(this.timer){
            clearInterval(this.timer)
        }
    }
  }
</script>